import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_community/utils/http.dart';
import 'package:flutter_community/utils/showToast.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  //设置加载状态
  bool _isLoading = true;
  //设置基地址
  String baseUrl = 'https://restapi.amap.com/v3';
  //设置key
  String apikey = '059938605acd7821f5c81a56a20a812a';
  //设置经纬度
  double _latitude = 0;
  double _longitude = 0;

  //设置地址和周边小区
  String currentAddress = '';
  @override
  void initState() {
    super.initState();
    requestLocationPermission();
    // //将经纬度进行逆解析->模拟器定位不到,使用默认的经纬度
    // reversesGeocoding(28.205514000000022, 112.94904999999994);
    // //获取附近小区
    // _searchPlaceAround(28.205514000000022, 112.94904999999994);
  }

  //判断是否授权
  Future<void> requestLocationPermission() async {
    PermissionStatus status = await Permission.location.request();
    if (status.isGranted) {
      // 权限未授予
      ToastMessage.showSuccess('位置权限授予');
      //获取经纬度
      getCurrentLocation();
    } else {
      // 权限未授予
      ToastMessage.showFail('位置权限未授予, 请去设置中心开启');
    }
  }

//授权后获取经纬度->判断Android、iOS/macOS 或 Web）配置不同的定位设置，
  getCurrentLocation() async {
    // late LocationSettings locationSettings;
    // if (defaultTargetPlatform == TargetPlatform.android) {
    //   // 针对Android平台，设置高精度定位、100米距离过滤、强制使用位置管理器等
    //   locationSettings = AndroidSettings(
    //       accuracy: LocationAccuracy.high,
    //       distanceFilter: 100,
    //       forceLocationManager: true,
    //       intervalDuration: const Duration(seconds: 10),
    //       foregroundNotificationConfig: const ForegroundNotificationConfig(
    //           notificationTitle:
    //               "Example app will continue to receive your location even when you aren't using it",
    //           notificationText: "Running in Background",
    //           enableWakeLock: true));
    // } else if (defaultTargetPlatform == TargetPlatform.iOS ||
    //     defaultTargetPlatform == TargetPlatform.macOS) {
    //   // 针对iOS和macOS平台，设置高精度定位、健身活动类型、100米距离过滤等
    //   locationSettings = AppleSettings(
    //     accuracy: LocationAccuracy.high,
    //     activityType: ActivityType.fitness,
    //     distanceFilter: 100,
    //     pauseLocationUpdatesAutomatically: true,
    //     // 只有在应用在后台启动时才设置为true
    //     showBackgroundLocationIndicator: false,
    //   );
    // } else if (kIsWeb) {
    //   // 针对Web环境，设置高精度定位、100米距离过滤、5分钟的最大年龄等
    //   locationSettings = WebSettings(
    //     accuracy: LocationAccuracy.high,
    //     distanceFilter: 100,
    //     maximumAge: const Duration(minutes: 5),
    //   );
    // } else {
    //   // 对于其他平台，默认设置高精度定位和100米距离过滤
    //   locationSettings = const LocationSettings(
    //     accuracy: LocationAccuracy.high,
    //     distanceFilter: 100,
    //   );
    // }
    try {
      // 使用配置好的定位设置获取当前位置
      Position position = await Geolocator.getCurrentPosition();
      // 显示成功获取到的纬度和经度
      ToastMessage.showSuccess('${position.latitude}, ${position.longitude}');
      // 真机调试->赋值
      setState(() {
        _latitude = position.latitude;
        _longitude = position.longitude;
        ToastMessage.showSuccess('经纬度获取:$_latitude, $_longitude');
        // 将经纬度进行逆解析->模拟器定位不到,使用默认的经纬度
        reversesGeocoding(_latitude, _longitude);
        // 获取附近小区
        _searchPlaceAround(_latitude, _longitude);
      });
    } catch (e) {
      // 处理可能出现的异常
      print(e.toString());
    }
  }

//逆地理解析->当前地址
  reversesGeocoding(double latitude, double longitude) async {
    try {
      //发请求获取数据
      final res = await http.get(
          '$baseUrl/geocode/regeo?key=$apikey&location=$longitude,$latitude');
      print(res);
      // ToastMessage.showSuccess('_解析的位置$_latitude, $_longitude');
      ToastMessage.showSuccess('_解析的位置$latitude, $longitude');
      setState(() {
        currentAddress = res['regeocode']['formatted_address'];
      });
    } catch (e) {
      ToastMessage.showFail('逆向解析失败');
    }
  }

//获取附近小区
  List nearbyCommunities = [];
  _searchPlaceAround(double latitude, double longitude) async {
    setState(() {
      _isLoading = true;
    });
//请求数据
    final res = await http.get(
        '$baseUrl/place/around?key=$apikey&location=$latitude,$longitude&radius=10000&types=住宅小区 ');
    print(res);
    ToastMessage.showSuccess('获取附近小区数据成功$latitude, $longitude');
    setState(() {
      nearbyCommunities = res['pois'];
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('选择社区'),
        backgroundColor: Colors.transparent,
      ),
      body: Container(
        padding: const EdgeInsets.all(10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            //当前地址
            const Text(
              '当前地址',
              style: TextStyle(fontSize: 18, color: Colors.grey),
            ),
            const SizedBox(height: 20),
            Container(
                color: Colors.white,
                padding: const EdgeInsets.only(left: 10, right: 10),
                height: 60,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                      child: Text(
                        currentAddress,
                        // style: const TextStyle(fontSize: 18),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        // reversesGeocoding(40.065956, 116.350077);
                        // _searchPlaceAround(40.065956, 116.350077);
                        //真机
                        // reversesGeocoding(_latitude, _longitude);
                        _searchPlaceAround(_latitude, _longitude);
                      },
                      child: const Row(
                        children: [
                          Icon(
                            Icons.location_searching,
                            color: Colors.blue,
                          ),
                          Text(
                            '重新定位',
                            style: TextStyle(color: Colors.blue),
                          )
                        ],
                      ),
                    )
                  ],
                )),
            const SizedBox(height: 10),
            //附近社区
            const Text(
              '附近社区',
              style: TextStyle(fontSize: 18, color: Colors.grey),
            ),
            const SizedBox(height: 10),
            //底部列表
            Expanded(
                child: _isLoading
                    ? const Center(
                        child: CircularProgressIndicator(
                          color: Color.fromARGB(255, 239, 170, 192),
                        ),
                      )
                    : Container(
                        padding: const EdgeInsets.all(10),
                        child: ListView.builder(
                          shrinkWrap: true,
                          itemCount: 10,
                          itemBuilder: (BuildContext context, int index) {
                            return Container(
                                color: Colors.white,
                                height: 60,
                                margin: const EdgeInsets.only(bottom: 10),
                                padding:
                                    const EdgeInsets.only(left: 10, right: 10),
                                //跳转到楼栋页
                                child: GestureDetector(
                                  onTap: () {
                                    Navigator.pushNamed(
                                        context, '/build_list', arguments: {
                                      'point': nearbyCommunities[index]['name']
                                    });
                                  },
                                  child: Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Expanded(
                                        child: Text(
                                          nearbyCommunities[index]['name'],
                                          // style: const TextStyle(fontSize: 18),
                                        ),
                                      ),
                                      const Icon(
                                        Icons.arrow_forward_ios,
                                        size: 20,
                                      ),
                                    ],
                                  ),
                                ));
                          },
                        ),
                      ))
          ],
        ),
      ),
    );
  }
}
